package demo.tcpClient;

import demo.TestMessageId;
import demo.protocol.MessageTestProto;
import net.jueb.protoServer.message.ProtoMessage;
import net.jueb.protoServer.message.ProtoMessage.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

public class TcpClientHandler extends SimpleChannelInboundHandler<ProtoMessage.Message>{
	
	
	protected static final InternalLogger log = InternalLoggerFactory.getInstance(TcpClientHandler.class);

	@Override
	public void channelActive(final ChannelHandlerContext ctx) throws Exception {
		for(int i=0;i<1;i++)
		{
			//构建扩展消息
			MessageTestProto.Request.Builder rb=MessageTestProto.Request.newBuilder();
			rb.setInfo("请求消息"+i+"ClientTime:"+System.currentTimeMillis());
			MessageTestProto.Request request=rb.build();
			//构建protoServer制定的主体消息
			ProtoMessage.Message.Builder mRb=ProtoMessage.Message.newBuilder();
			mRb.setMsgId(TestMessageId.Request);
			mRb.setExtension(MessageTestProto.request, request);
			ProtoMessage.Message message=mRb.build();
			ctx.channel().writeAndFlush(message);
			log.debug("ClientTime="+System.currentTimeMillis()+"时,第"+i+"次消息发送完成!");
		}
		
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Message msg)throws Exception 
	{
		MessageTestProto.Response response=msg.getExtension(MessageTestProto.response);
		log.info("ClientTime="+System.currentTimeMillis()+"时,收到服务端回复:"+response.getInfo());
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

}
